﻿using System;
using System.Collections.Generic;

namespace Goooodbye.Core.SharedKernel
{
    public abstract class GenericService<E, M, Q> : IService<E, M, Q>
        where E : Entity
        where M : IModel
        where Q : PagingQuery
    {
        private IRepository<E, M, Q> repository;

        public GenericService(IRepository<E, M, Q> repository)
        {
            this.repository = repository;
        }

        public virtual M Get(string id)
        {
            return repository.Select(id);
        }

        public virtual PagedList<M> Query(Q query = null)
        {
            PagedList<M> ret = new PagedList<M>();
            ret.Items = repository.Select(query);
            ret.Total = repository.Count(query);
            ret.PageCount = query != null && query.Pageable ? (int)Math.Ceiling((ret.Total + 0.0) / query.PageSize) : 1;
            return ret;
        }

        public virtual bool Remove(string id)
        {
            return repository.Delete(id) > 0;
        }

        public virtual bool Save(E entity)
        {
            int affected;
            if (String.IsNullOrEmpty(entity.Id))
            {
                entity.Id = Guid.NewGuid().ToString();
                affected = repository.Insert(entity);
            }
            else
            {
                affected = repository.Update(entity);
            }
            return affected > 0;
        }

        public virtual IList<string> Validate(E entity)
        {
            return new List<string>();
        }
    }
}
